/*
 * Copyright (c) 2018 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dyzx.hbb.aliyun.product;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONObject;
import com.dyzx.hbb.modules.wms.entity.WmsProduct;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;


/**
 * 阿里云 SMS 客户端.
 *
 * @author cn-src
 */
public class ProductClient {

    private String appKey;
    private String appSecret;
    private String appCode;

    public ProductClient(String appKey, String appSecret, String appCode) {

        this.appKey = appKey;
        this.appSecret = appSecret;
        this.appCode = appCode;
    }


    public WmsProduct send(String code) {
        String host = "https://jisutxmcx.market.alicloudapi.com";
        String path = "/barcode2/query";
        String method = "GET";//GET/POST 任意
        String appcode = this.appCode;
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("barcode", code);


        try {
            HttpRequest post = HttpRequest.get(host + path + "?barcode=" + code);

            post.addHeaders(headers);

            post.formStr(querys);
            HttpResponse response = post.execute();
            String body = response.body();
            System.out.println(body);
            JSONObject json = JSONObject.parseObject(body);
            int status = json.getIntValue("status");
            if (status == 0) {
                JSONObject data = json.getJSONObject("result");
                System.out.println(data.toJSONString());
                return jsonToWmsProduct(data);
            } else {
                return null;
            }

            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity(),"utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private WmsProduct jsonToWmsProduct(JSONObject data) {
        String barcode = data.containsKey("barcode") ? data.getString("barcode") : data.getString("code");
        WmsProduct product = new WmsProduct();
        product.setName(data.getString("name"));
        product.setInternalCode(barcode);
        product.setDescription(data.getString("description"));
        // product.setSupplierId(data.getLong("supplier_id"));
        // product.setUnitOfMeasure(data.getString("unit_of_measure"));
        product.setDimensions(data.getString("type"));
        product.setWeight(toStrLong(data.getString("type")));
        //   product.setDimensions(data.getString("dimensions"));
        product.setImageUrl(data.getString("pic"));
        //    product.setIsActive(data.getIntValue("is_active"));
        //   product.setQualityTraceFlag(data.getIntValue("quality_trace_flag"));
        //  product.setStandardCompliance(data.getString("standard_compliance"));
        product.setAmt(priceToLong(data.getString("price")));
        product.setGrossweight(toStrLong(data.getString("grossweight")));
        product.setNetweight(toStrLong(data.getString("netweight")));
        product.setWidth(toStrLong(data.getString("width")));
        product.setHeight(toStrLong(data.getString("height")));
        product.setDepth(toStrLong(data.getString("depth")));
        product.setOrigincountry(data.getString("origincountry"));
        product.setOriginplace(data.getString("originplace"));
        product.setAssemblycountry(data.getString("assemblycountry"));
        product.setCompany(data.getString("company"));
        product.setEname(data.getString("ename"));
        product.setUnspsc(data.getString("unspsc"));
        product.setBrand(data.getString("brand"));
        product.setNetcontent(data.getString("netcontent"));
        return product;
    }

    private Long priceToLong(String str) {
        if (StringUtils.isNotEmpty(str)) {
            str = str.replaceAll("[a-zA-Z]", "");
            str = str.trim();
            double d = Double.parseDouble(str);
            return (long) (d * 100);
        } else {
            return null;
        }

    }

    private Long toStrLong(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        //330ml,60 MM,60mm,60mm,
        str = str.replace(" ", "");
        str = str.replace(",", ".");
        str = str.replace(".", "");
        str = str.replace("mm", "");
        str = str.replace("ML", "");
        str = str.replace("m", "");
        str = str.replace("L", "");
        str = str.replace("M", "");
        str = str.replace("mm", "");
        str = str.replace("M", "");
        str = str.replace("L", "");
        //a-zA-Z replaceAll("[a-zA-Z]","");
        str = str.replaceAll("[a-zA-Z]", "");
        str = str.trim();
        //, ，/, \, - ,@,#,$,%,^,&,*,(,),+_等字符替换为0
        if (str.contains(",") || str.contains("，") || str.contains("/") || str.contains("\\") || str.contains("-") || str.contains("@") || str.contains("#") || str.contains("$") || str.contains("%") || str.contains("^") || str.contains("&") || str.contains("*") || str.contains("(") || str.contains(")") || str.contains("+") || str.contains("_")) {
          return  null;
        }else{
            return Long.parseLong(str);
        }
        //，


    }


}
